package com.sc.web.gwt.server.util;

import com.sc.web.gwt.server.persistence.AuthenticatorPersistence;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class SeedGenerator {
    public static String getSeed() {
        AuthenticatorPersistence authenticatorPersistence = new AuthenticatorPersistence();
        List<String> currentSeedList = new ArrayList<String>();
        currentSeedList = authenticatorPersistence.getAllSeed();
        String seed = new String();

        if (currentSeedList != null && currentSeedList.size() > 0) {
            boolean isExist = true;

            while (isExist) {
                isExist = false;
                seed = randomSeed();

                for (Iterator<String> iter = currentSeedList.iterator(); iter.hasNext(); ) {
                    String var = iter.next();
                    if (var.equalsIgnoreCase(seed)) {
                        isExist = true;
                        break;
                    }
                }
            }
        } else {
            return randomSeed();
        }

        return seed;
    }

    public static String convertToString(int i) {
        return "" + i;
    }

    private static String randomSeed() {
        String seed = "";
        Random random = new Random();
        int tmp;
        for (int i = 1; i <= 12; i++) {
            tmp = random.nextInt(9);
            if (tmp == 0) {
                seed += "0";
            } else {
                seed += tmp;
            }
        }
        return seed;
    }

    private static int randomIntegerFromSpecificRange(int aStart, int aEnd, Random aRandom) {
        if (aStart > aEnd) {
            throw new IllegalArgumentException("Start cannot exceed End.");
        }
        //get the range, casting to long to avoid overflow problems
        long range = (long) aEnd - (long) aStart + 1;
        // compute a fraction of the range, 0 <= frac < range
        long fraction = (long) (range * aRandom.nextDouble());
        int randomNumber = (int) (fraction + aStart);

        return randomNumber;
    }
}

